package com.example.mqttclient;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MainActivity extends AppCompatActivity {

    private TextView connectState;
    private String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectState = findViewById(R.id.connect_state);

    }
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.i(TAG, "connect success");
            try {
                client.subscribe("/test",0);
                client.publish("/test","hello".getBytes(),0,false);
            } catch (MqttException e) {
                e.printStackTrace();
            }

        }
        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            Log.i(TAG, "connect fail:" + arg1.toString());
        }
    };
    private MqttCallback mqttCallback = new MqttCallback() {
        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.i(TAG, "messageArrived:" + new String(message.getPayload()));
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            Log.i(TAG, "publish ok:" + arg0.toString());
        }
        @Override
        public void connectionLost(Throwable arg0) {
            Log.i(TAG, "connectionLost:" + arg0.toString());
        }
    };
    MqttAndroidClient client;
    MqttConnectOptions conOpt = new MqttConnectOptions();
    private void connect() {
        client = new MqttAndroidClient(this, "tcp://172.16.56.15:1883", "clientId");
        client.setCallback(mqttCallback);// 设置MQTT监听并且接受消息
        conOpt.setCleanSession(true);// 清除缓存
        conOpt.setConnectionTimeout(10);// 设置超时时间，单位：秒
        conOpt.setKeepAliveInterval(20);// 心跳包发送间隔，单位：秒
        conOpt.setUserName("userName");
        conOpt.setPassword("password".toCharArray());
        try {
            if(!client.isConnected())
                client.connect(conOpt, null, iMqttActionListener);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }



}
